package com.chucang.shucang.ttp.service;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.chucang.shucang.ttp.feign.vo.RealNameAuthVO;
import com.chucang.shucang.ttp.vo.RealNameAuthResVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author flitsneak
 * @email flitsneak@gmail.com
 * @date 2022/10/6 22:40
 * @description 实名认证服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RealNameAuthService {

    @Value("${real.auth.host}")
    private String host;

    @Value("${real.auth.path}")
    private String path;

    @Value("${real.auth.appcode}")
    private String appcode;

    private static final String AUTHORIZATION = "Authorization";
    private static final String APP_CODE = "APPCODE ";
    private static final String CONTENT_TYPE = "Content-Type";
    private static final String WWW_FORM_URL = "application/x-www-form-urlencoded; charset=UTF-8";

    public RealNameAuthResVO doAuth(RealNameAuthVO realNameAuthVO) {
        Map<String, String> headers = new HashMap<>(2);
        headers.put(AUTHORIZATION, APP_CODE + appcode);
        headers.put(CONTENT_TYPE, WWW_FORM_URL);
        Map<String, Object> bodys = new HashMap<>(2);
        bodys.put("cardNo", realNameAuthVO.getIdentityCard());
        bodys.put("realName", realNameAuthVO.getRealName());

        String body = HttpRequest.post(host + path)
                .headerMap(headers, true)
                .form(bodys)
                .timeout(2000)
                .execute()
                .body();
        return JSONUtil.toBean(body, new TypeReference<>() {
        }, true);
    }
}
